package servlet;

import model.DBUtil;
import model.Guser;
import model.Puser;
import model.Ruser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/glogin")
public class 管理员登录  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String gphone = req.getParameter("gphone");
        String gpassword = req.getParameter("gpassword");
        System.out.println(gphone);
        System.out.println(gpassword);
        PrintWriter out = resp.getWriter();
        try {
            // 2. 通过 MySQL 查询，得到用户对象
            Guser guser = query(gphone, gpassword);
            if (guser == null) {
                // 查不到对应的用户，代表用户名密码错误
                out.print("<script language='javascript'>alert('Wrong password. Login again!!');window.location.href='/rlogin.html';</script>");
                return;
            }
            HttpSession session = req.getSession();
            session.setAttribute("gcurrentUser", guser);
            resp.sendRedirect("/");
        }catch (SQLException exc) {
            throw new ServletException(exc);
        }
    }
    private Guser query(String gphone, String gpassword) throws SQLException {
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT guid,gphone FROM guser WHERE gphone = ? AND gpassword = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, gphone);
                s.setString(2, gpassword);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    Guser guser = new Guser();
                    guser.guid = rs.getInt("guid");
                    guser.gphone = rs.getString("gphone");


                    return guser;
                }
            }

        }
    }

}


